import storage from './storage'
import config from './config'
import env from './env'

let loadingCount = 0

const showLoading = show => {
    if (show) {
        loadingCount++
        uni.showLoading()
        return show
    }
}

const hideLoading = show => {
    if (show) {
        loadingCount--
        setTimeout(()=>{
            if (loadingCount === 0) {
                uni.hideLoading()
            }
        })
    }
}

const request = options => {
    const headers = options.headers ?? {}
    const token = storage.get(storage.token)
    if (token) {
        headers[config.tokenName] = token
    }
    const loadingToken = showLoading(options.loading ?? true)
    
    return new Promise((resolve, reject) => {
        uni.request({
            url: options.url ?? env.baseUrl + options.uri,
            method: options.method ?? 'GET',
            header: headers, data: options.data,
            timeout: options.timeout ?? 10000,
            enableCache: options.enableCache ?? false,
            success: res => {
                resolve(res.data)
            },
            fail: error => {
                reject(error)
                console.error('request', error)
            },
            complete: () => {
                hideLoading(loadingToken)
            }
        })
    })
}

export default {
    request,
    get: (uri, params = null, options = {}) => request({
        method: 'GET',
        uri: uri,
        data: params,
        ...options
    }),
    post: (uri, data = null, options = {}) => request({
        method: 'POST',
        uri: uri,
        data: data,
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        },
        ...options
    }),
    put: (uri, data = null, options = {}) => request({
        method: 'PUT',
        uri: uri,
        data: data,
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        },
        ...options
    }),
    delete: (uri, data = null, options = {}) => request({
        method: 'DELETE',
        uri: uri,
        data: data,
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        },
        ...options
    })
}
